#include <my/Window/Window.h>
#include <my/Window/GameState.h>
#include <my/Logger/Logger.h>
#include <my/Config.h>
#include <iostream>

using namespace std;

namespace my {

    Window::Window(const std::string& title, int width, int height, unsigned long style) :
    sf::RenderWindow(sf::VideoMode(width, height), title, style),
    EventHandling(),
    _aboutToPop(false),
    _states()
    {
        try {
            connect("exit", boost::bind(&sf::RenderWindow::Close, this));
        }
        catch(...) {
            Logger::write(ToString("my::Window (" + ToString(__LINE__) + ") connect failed."));
        }
    }

    Window::~Window()
    {

    }

    void  Window::start()
    {
        while (IsOpened())
        {
            // Deleting old state if have to be
            pop();
            // Do nothing if there are no states
            if(!_states.empty())
            {
                // Process events
                sf::Event event;
                while (PollEvent(event))
                {
                    _states.top()->update(event);
                }

                // Clear screen
                Clear();

                // Draw the sprite
                _states.top()->draw(*this);

                // Update the window
                Display();
            }
        }
    }

    void  Window::pushState(GameState* state)
    {
        if(state)
            _states.push(state);
    }

    void  Window::popState()
    {
        _aboutToPop = true;
    }

    void  Window::pop()
    {
        if(_aboutToPop)
        {
            _states.pop();
            _aboutToPop = false;
        }

        if(_states.empty())
        {
            emit("exit");
            Logger::write(ToString("my::Window (" + ToString(__LINE__) + ") No more game state for window. Exiting program."));
        }
    }

}
